//
//  VideoViewController.m
//  LOL_JewelBox
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoViewController.h"
#import "VideoView.h"
#import "videoModel.h"
#import "HotVideoModel.h"
#import "VideoCell.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "DetailVideoViewController.h"
#import "MJRefresh.h"
#import "HMSegmentedControl.h"
#import "CommentModel.h"
#import "CommentVideoCell.h"
#import "DetailCommentViewController.h"
#pragma mark 抽屉效果
#import "RNFrostedSidebar.h"
#import "UserViewController.h"
#import "VideoCollectViewController.h"
#import "CombatViewController.h"
#import "OursViewController.h"
#import "GMDCircleLoader.h"

@interface VideoViewController ()<RNFrostedSidebarDelegate>

@property(nonatomic, retain)NSMutableArray *newsetArr;
@property(nonatomic, retain)NSMutableArray *hotpartArr;
@property(nonatomic, retain)NSMutableArray *commentArr;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *transformArr;
@property(nonatomic, retain)NSMutableArray *comArr;
@property(nonatomic,retain)NSMutableArray *competitionArr;
@property(nonatomic, retain)HMSegmentedControl *segmentedControl;
@property(nonatomic, assign)NSInteger pageNum;
@property(nonatomic, retain)UICollectionView *comCollectionView;
// 抽屉效果
@property (nonatomic, strong) NSMutableIndexSet *optionIndices;

@end

@implementation VideoViewController

- (void)dealloc
{
    [_newsetArr release];
    [_hotpartArr release];
    [_commentArr release];
    [_tableView release];
    [_transformArr release];
    [_segmentedControl release];
    [_comArr release];
    [_competitionArr release];
    [super dealloc];
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.newsetArr = [NSMutableArray array];
        self.commentArr = [NSMutableArray array];
        self.hotpartArr = [NSMutableArray array];
        self.transformArr = [NSMutableArray array];
        self.comArr = [NSMutableArray array];
        self.competitionArr = [NSMutableArray array];
         self.optionIndices = [NSMutableIndexSet indexSet];
        self.pageNum = 2;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self GetVideo];

    // Do any additional setup after loading the view.

    VideoView *videoView = [[ VideoView alloc]initWithFrame:CGRectMake(0, 0, VIEWWIDTH, VIEWHEIGHT)];
    [self.view addSubview:videoView];
    [videoView release];

    self.segmentedControl = [[HMSegmentedControl alloc]initWithSectionTitles:@[@"最新", @"热点", @"娱乐", @"解说", @"赛事"]];
    self.segmentedControl.frame = CGRectMake(0, 0, VIEWWIDTH, (VIEWHEIGHT - 64- 49) *0.05415);
    [self.segmentedControl addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    [self.segmentedControl setBackgroundColor:[UIColor lightGrayColor]];
    [self.segmentedControl setTextColor:[UIColor whiteColor]];
    [self.segmentedControl setSelectionIndicatorColor:[UIColor blackColor]];
    self.navigationItem.title = @"视频";
  
    [videoView addSubview:self.segmentedControl];
    [_segmentedControl release];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake((VIEWHEIGHT - 64 -49) *0.18051, (VIEWHEIGHT - 64 - 49) *0.25271);
    //最小行间距
    flowLayout.minimumLineSpacing = 5;
    //最小列间距
    flowLayout.minimumInteritemSpacing = 0.1;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.comCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, (VIEWHEIGHT - 64- 49) *0.05415, VIEWWIDTH, (VIEWHEIGHT - 64 -49) *0.96931) collectionViewLayout:flowLayout];
//    NSLog(@"%g", VIEWHEIGHT);
    self.comCollectionView.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:0.98];
    [videoView addSubview:self.comCollectionView];
    [_comCollectionView release];
    //签订协议
    
    self.comCollectionView.dataSource = self;
    self.comCollectionView.delegate = self;
    
    [self.comCollectionView registerClass:[CommentVideoCell class] forCellWithReuseIdentifier:@"ccc"];
    [self.comCollectionView registerClass:[CommentVideoCell class] forCellWithReuseIdentifier:@"haha"];
    [self.comCollectionView registerClass:[CommentVideoCell class] forCellWithReuseIdentifier:@"sss"];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, (VIEWHEIGHT - 64- 49) *0.05415, VIEWWIDTH, (VIEWHEIGHT - 64 -49) *0.94585)];
    [videoView addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = (VIEWHEIGHT - 64-49) *0.18051;
    [_tableView release];
#pragma mark 上拉刷新下拉加载
    [self addHeader];
    [self addFooter];
#pragma mark 添加抽屉效果
    [self createDesk];
    [GMDCircleLoader hideFromView:self.view animated:YES];
}

- (void)createDesk
{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"菜单" style:UIBarButtonItemStylePlain target:self action:@selector(deskAction:)];
}

// deskAction 抽屉效果
- (void)deskAction:(id)sender
{
    NSArray *images = @[[UIImage imageNamed:@"战斗力"],[UIImage imageNamed:@"设置"],[UIImage imageNamed:@"收藏"],[UIImage imageNamed:@"关于我们"]];
    
    NSArray *colors = @[[UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1],
                        [UIColor colorWithRed:255/255.f green:137/255.f blue:167/255.f alpha:1],
                        [UIColor colorWithRed:126/255.f green:242/255.f blue:195/255.f alpha:1],
                        [UIColor colorWithRed:119/255.f green:152/255.f blue:255/255.f alpha:1]];
    
    
    RNFrostedSidebar *callout = [[RNFrostedSidebar alloc] initWithImages:images selectedIndices:self.optionIndices borderColors:colors];
    callout.borderWidth = 5;
    callout.delegate = self;
    [callout show];
}

#pragma mark 抽屉效果点击事件
- (void)sidebar:(RNFrostedSidebar *)sidebar didTapItemAtIndex:(NSUInteger)index
{
    if (index == 0) {
        CombatViewController *combat = [[CombatViewController alloc] init];
        [self.navigationController pushViewController:combat animated:YES];
        [combat release];
        [sidebar dismiss];
    }

    if (index == 1) {
        UserViewController *userView = [[UserViewController alloc]init];
        [self.navigationController pushViewController:userView animated:YES];
        self.tabBarController.tabBar.hidden = YES;
        [userView release];
        [sidebar dismiss];
    }
     if (index == 2) {
        VideoCollectViewController *collectView = [[VideoCollectViewController alloc]init];
        [self.navigationController pushViewController:collectView animated:YES];
        self.tabBarController.tabBar.hidden = YES;
        [collectView release];
        [sidebar dismiss];
    }

    if (index == 3) {
        OursViewController *our = [[OursViewController alloc] init];
        [self.navigationController pushViewController:our animated:YES];
        [our release];
        [sidebar dismiss];
    }
}

- (void)sidebar:(RNFrostedSidebar *)sidebar didEnable:(BOOL)itemEnabled itemAtIndex:(NSUInteger)index {
    if (itemEnabled) {
        [self.optionIndices addIndex:index];
    }
    else {
        [self.optionIndices removeIndex:index];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger index = self.segmentedControl.selectedIndex;
    if (index == 2 || index == 3 ) {
        return self.transformArr.count;
    }else if (index == 4)
    {
        return self.transformArr.count;
    }
    else
    {
        return 0;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger index = self.segmentedControl.selectedIndex;
    if (index == 2) {
        CommentVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ccc" forIndexPath:indexPath];
        
        CommentModel *comMo = self.transformArr[indexPath.row];
        cell.ComLabel.text = comMo.name;
        NSURL *url = [NSURL URLWithString:comMo.pic_url];
        [cell.ComImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"占位图"]];
        return cell;
    }else if (index == 3)
    {
        CommentVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"haha" forIndexPath:indexPath];
        
        CommentModel *comMo = self.transformArr[indexPath.row];
        cell.ComLabel.text = comMo.name;
        NSURL *url = [NSURL URLWithString:comMo.pic_url];
        [cell.ComImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"占位图"]];
        return cell;
    }else if (index == 4)
    {
        CommentVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"sss" forIndexPath:indexPath];
        
        CommentModel *comMo = self.transformArr[indexPath.row];
        cell.ComLabel.text = comMo.name;
        NSURL *url = [NSURL URLWithString:comMo.pic_url];
        [cell.ComImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"占位图"]];
        return cell;
        
    }
    else
    {
        return nil;
    }
}

-(void)addHeader{
    [self.tableView headerBeginRefreshing];
    
    [self.tableView  addHeaderWithCallback:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            
            [self.tableView reloadData];
            [self.tableView headerEndRefreshing];
        });
    }];
    
}


-(void)addFooter
{
    NSInteger index = self.segmentedControl.selectedIndex;
   
    [self.tableView addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (index == 0) {
                NSString *temp = [NSString stringWithFormat:@"http://lol.video.luckyamy.com/api/?cat=home&page=%ld&ap=lolg&ver=1.1", self.pageNum];
                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
                [manager GET:temp parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSMutableArray *arr = responseObject;
                    for (NSMutableDictionary *dic in arr) {
                        videoModel *videoMo = [[videoModel alloc]init];
                        [videoMo setValuesForKeysWithDictionary:dic];
                        [self.transformArr addObject:videoMo];
                        [videoMo release];
                    }
                    self.pageNum++;
                    //        NSLog(@"%@",self.newsetArr);
                    [self.tableView reloadData];
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"cuowu");
                }];
            }else if (index == 1){
                NSString *temp = [NSString stringWithFormat:@"http://lol.video.luckyamy.com/api/?cat=home&type=random&p=%ld&time=1413005025&ap=lolg&ver=1.1", self.pageNum];
                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
                [manager GET:temp parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSMutableArray *arr = responseObject;
                    for (NSMutableDictionary *dic in arr) {
                        HotVideoModel *hotVideo = [[HotVideoModel alloc]init];
                        [hotVideo setValuesForKeysWithDictionary:dic];
                        [self.transformArr addObject:hotVideo];
                        [hotVideo release];
                    }
                    
                    self.pageNum++;
                    //        NSLog(@"%@",self.newsetArr);
                    [self.tableView reloadData];
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"cuowu");
                }];
                
            }
            
            [self.tableView   footerEndRefreshing];
        });

    }];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.transformArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index = self.segmentedControl.selectedIndex;
    if ( index == 0)
    {
        
        static NSString *reuse = @"reuse";
        VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (cell == nil) {
            cell = [[[VideoCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse]autorelease];
        }
        videoModel *videoMo = self.transformArr[indexPath.row];
        NSURL *url = [NSURL URLWithString:videoMo.img];
        [cell.videoImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"占位图"]];
        cell.titleLabel.text = videoMo.title;
        cell.numLabel.text = videoMo.num;
        cell.durationLabel.text = videoMo.duration;
        cell.timeImageView.image = [UIImage imageNamed:@"Time"];
        cell.clickImageVIew.image = [UIImage imageNamed:@"Click"];
        cell.selectionStyle = NO;
        return cell;
    }else if (index == 1)
    {
        static NSString *night = @"night";
        VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:night];
        if (cell == nil) {
            cell = [[[VideoCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:night]autorelease];
        }
        HotVideoModel *hotVideo = self.transformArr[indexPath.row];
        NSURL *url = [NSURL URLWithString:hotVideo.img];
        [cell.videoImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"占位图"]];
        cell.titleLabel.text = hotVideo.title;
        cell.numLabel.text = hotVideo.num;
        cell.durationLabel.text = hotVideo.duration;
        cell.timeImageView.image = [UIImage imageNamed:@"Time"];
        cell.clickImageVIew.image = [UIImage imageNamed:@"Click"];
         cell.selectionStyle = NO;
        return cell;
    }else
    {
        return nil;
    }
}






-(void)segClick:(HMSegmentedControl *)click
{
    [self.transformArr removeAllObjects];
    NSInteger index = click.selectedIndex;
    switch (index) {
        case 0:
            self.tableView.hidden = NO;
            self.comCollectionView.hidden = YES;
            break;
        case 1:
            self.tableView.hidden = NO;
            self.comCollectionView.hidden = YES;
            break;
            
        case 2:
            self.tableView.hidden = YES;
            self.comCollectionView.hidden = NO;
            break;
            
        case 3:
            self.tableView.hidden = YES;
            self.comCollectionView.hidden = NO;
            break;
        case 4:
            self.tableView.hidden = YES;
            self.comCollectionView.hidden = NO;
            break;
        default:
            break;
    }
    if (index == 0) {
        for (videoModel *temp in self.newsetArr) {
            [self.transformArr addObject:temp];
        }
        [self.tableView reloadData];
    }else if (index == 1)
    {
        for (HotVideoModel *temp in self.hotpartArr) {
            [self.transformArr addObject:temp];
        }
        [self.tableView reloadData];
    }else if (index == 2){
        for (CommentModel *temp in self.comArr) {
            [self.transformArr addObject:temp];
        }
        [self.comCollectionView reloadData];
    }else if (index == 3){
        for (CommentModel *temp in self.commentArr) {
            [self.transformArr addObject:temp];
        }
        [self.comCollectionView reloadData];
    }else if (index == 4){
        for (CommentModel *temp in self.competitionArr) {
            [self.transformArr addObject:temp];
        }
        [self.comCollectionView reloadData];
    }
}

-(void)GetVideo
{
    
    [GMDCircleLoader setOnView:self.view withTitle:@"英雄数据加载中..." animated:YES];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://lol.video.luckyamy.com/api/?cat=home&page=1&ap=lolg&ver=1.1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = responseObject;
        for (NSMutableDictionary *dic in arr) {
            videoModel *videoMo = [[videoModel alloc]init];
            [videoMo setValuesForKeysWithDictionary:dic];
            [self.newsetArr addObject:videoMo];
            [videoMo release];
        }
        [self.tableView reloadData];
      self.segmentedControl.selectedIndex  = 0;
        [self segClick:self.segmentedControl];
        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"cuowu");
    }];


    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1 GET:@"http://lol.video.luckyamy.com/api/?cat=home&type=random&p=1&time=1413005025&ap=lolg&ver=1.1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = responseObject;

        for (NSMutableDictionary *dic in arr) {
            HotVideoModel *hotVideo = [[HotVideoModel alloc]init];
            [hotVideo setValuesForKeysWithDictionary:dic];
            [self.hotpartArr addObject:hotVideo];
            [hotVideo release];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"cuowu");
    }];
    
    AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
    [manager2 GET:@"http://lol.zhangyoubao.com/apis/rest/CatalogsService/all?cattype=video&i_=70CCD531-7601-4F9D-B1E8-130796BF8400&t_=1430186550&p_=21995&v_=40040306&d_=ios&osv_=8.3&version=0&a_=lol" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *arr = dic[@"data"];
        NSMutableDictionary *dic2 = arr[0];
        NSMutableArray *tempArr = dic2[@"catword_id"];
        for (NSMutableDictionary *dic in tempArr) {
            CommentModel *comment = [[CommentModel alloc] init];
            [comment setValuesForKeysWithDictionary:dic];
            [self.comArr addObject:comment];
            [comment release];
        }
//        NSLog(@"%@", self.comArr);
        [self.comCollectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    AFHTTPRequestOperationManager *manager3 = [AFHTTPRequestOperationManager manager];
    [manager3 GET:@"http://lol.zhangyoubao.com/apis/rest/CatalogsService/all?cattype=video&i_=70CCD531-7601-4F9D-B1E8-130796BF8400&t_=1430186550&p_=21995&v_=40040306&d_=ios&osv_=8.3&version=0&a_=lol" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *arr = dic[@"data"];
        NSMutableDictionary *dic2 = arr[1];
        NSMutableArray *tempArr = dic2[@"catword_id"];
        for (NSMutableDictionary *dic in tempArr) {
            CommentModel *comment = [[CommentModel alloc] init];
            [comment setValuesForKeysWithDictionary:dic];
            [self.commentArr addObject:comment];
            [comment release];
        }
        //        NSLog(@"%@", self.comArr);
        [self.comCollectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    AFHTTPRequestOperationManager *manager4 = [AFHTTPRequestOperationManager manager];
    [manager4 GET:@"http://lol.zhangyoubao.com/apis/rest/CatalogsService/all?cattype=video&i_=70CCD531-7601-4F9D-B1E8-130796BF8400&t_=1430186550&p_=21995&v_=40040306&d_=ios&osv_=8.3&version=0&a_=lol" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *arr = dic[@"data"];
        NSMutableDictionary *dic2 = arr[2];
        NSMutableArray *tempArr = dic2[@"catword_id"];
        for (NSMutableDictionary *dic in tempArr) {
            CommentModel *comment = [[CommentModel alloc] init];
            [comment setValuesForKeysWithDictionary:dic];
            [self.competitionArr addObject:comment];
            [comment release];
        }
        [self.comCollectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index = self.segmentedControl.selectedIndex;
    if (index == 0) {
        DetailVideoViewController *sec = [[DetailVideoViewController alloc]init];
        [self.navigationController pushViewController:sec animated:YES];
        [sec release];
        videoModel *videoMo = self.transformArr[indexPath.row];
        sec.url = videoMo.url;
        sec.title = videoMo.title;
    }else if (index == 1){
        DetailVideoViewController *sec = [[DetailVideoViewController alloc]init];
        [self.navigationController pushViewController:sec animated:YES];
        [sec release];
        HotVideoModel *hotVideo = self.transformArr[indexPath.row];
        sec.url = hotVideo.url;
        sec.title = hotVideo.title;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
            DetailCommentViewController *comVideo = [[DetailCommentViewController alloc]init];
            [self.navigationController pushViewController:comVideo animated:YES];
            [comVideo release];
            CommentModel *comMo = self.transformArr[indexPath.row];
            comVideo.id = comMo.id;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
